#include "ctcascader.h"

CTCascader::CTCascader(QWidget *parent)
    : QWidget{parent}
{
    QVBoxLayout *layout = new QVBoxLayout();
    m_combobox.addItem("请选择");
    m_btn.setText("请选择");
    //layout->addWidget(&m_combobox);
    layout->addWidget(&m_btn);
    layout->setContentsMargins(0,0,0,0);
    this->setLayout(layout);
    //connect(&m_combobox, QOverload<int>::of(&QComboBox::activated),this, &CTCascader::slotPopMenu);
    connect(&m_btn, &QPushButton::clicked, this, &CTCascader::slotPopMenu);

}

void CTCascader::setCascadedItems(const QMap<QString, QVector<QString> > &items)
{
    m_contextMenu.clear();
    QString strParam;
    QMap<QString, QVector<QString>>::const_iterator iter;
    for (iter = items.constBegin();iter!= items.constEnd(); ++iter)
    {
        //qDebug() << iter.key() << iter.value();
        QAction *menuone = m_contextMenu.addAction(iter.key());
        QVector<QString> vs = iter.value();
        QMenu *subMenu = new QMenu();
        foreach(QString  str, vs)
        {
            //qDebug() << str;
            QAction * action = subMenu->addAction(str);
            strParam = iter.key()+"/" + str;
            //strParam =  str;
            connect(action, &QAction::triggered, [=]{slotRewriteToBtn(strParam);});
        }
        if(!subMenu->isEmpty())
        {
            menuone->setMenu(subMenu);
        }
    }
}

void CTCascader::setCascadedItemsNew(const QMap<QString, QStringList* > &items)
{
    m_contextMenu.clear();
    QString strParam;
    QMap<QString, QStringList*>::const_iterator iter;
    for (iter = items.constBegin();iter!= items.constEnd(); ++iter)
    {
        //qDebug() << iter.key() << iter.value();
        QAction *menuone = m_contextMenu.addAction(iter.key());
        QStringList vs = *iter.value();
        QMenu *subMenu = new QMenu();
        foreach(QString  str, vs)
        {
            //qDebug() << str;
            QAction * action = subMenu->addAction(str);
            //strParam = iter.key()+"/" + str;
            strParam =  str;
            connect(action, &QAction::triggered, [=]{slotRewriteToBtn(strParam);});
        }
        if(!subMenu->isEmpty())
        {
            menuone->setMenu(subMenu);
        }
    }
}

void CTCascader::slotPopMenu()                     //槽函数定义
{
    QPoint pos = m_btn.mapToGlobal(m_btn.rect().bottomLeft());
    m_contextMenu.popup( pos);
}
void CTCascader::slotRewriteToBtn(QString selectStr)                     //槽函数定义
{
    //qDebug() << "自定义选项1被选中"<<selectStr;
    m_btn.setText(selectStr);
    emit dcascadedSelected(selectStr);
}
